<template>
  <div class="pro-task-detail">
    <div class="task-title-top">
      <div class="title-top-left">
        <div class="title-name">{{ detailData.projectTaskName }}</div>
        <el-progress :percentage="detailData.taskProgress"></el-progress>
      </div>
      <div class="title-top-right">
        <el-button type="text" v-if="isShowEdit" @click="UpdateProgress()">{{
          $t('projectManage.taskManageView.updateProgress')
        }}</el-button>
        <el-button type="text" v-if="isShowEdit" @click="editTaskDetail()">
          <i class="el-icon-edit"></i>{{$t('common.projectManage.detail.editTask')}}
        </el-button>
      </div>
    </div>
    <!-- 更新进度 -->
    <update-progress-dialog ref="UpdateProgressDialog" :canFinish="canFinish" :taskProgress="detailData.taskProgress" @submit="handelProgressSubmit"></update-progress-dialog>

    <div class="tab-wrap">
      <el-tabs type="type-card" v-model="activeName">
        <el-tab-pane :label="$t('common.projectManage.detail.tab.workLog')" name="record">
          <!-- 工作日志 -->
          <div class="tab-item">
            <projectTypeWorkLog 
              v-if="pageInit"
              :projectId="detailData.projectId" 
              :templateId="detailData.projectTypeId"
              :taskId="detailData.id" 
              :btnAuth="btnAuth"
              :isTaskCancelState="isTaskCancelState"
            ></projectTypeWorkLog>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="$t('common.projectManage.detail.taskDetail.title')" name="task">
          <div class="tab-item">
            <form-view :fields="fields" :value="detailData">
                <!-- 任务编号 S -->
                <template slot="missionNo" slot-scope="{ field, value }">
                  <div class="form-view-row">
                    <label>{{ field.displayName }}</label>
                    <div class="form-view-row-content"> {{ detailData.taskNumber }} </div>
                  </div>
                </template>
                <!-- 任务编号 E -->

                <!-- 任务名称 S -->
                <template slot="missionName" slot-scope="{ field, value }">
                  <div class="form-view-row">
                    <label>{{ field.displayName }}</label>
                    <div class="form-view-row-content"> {{ detailData.projectTaskName }} </div>
                  </div>
                </template>
                <!-- 任务名称 E -->

                <!-- 负责人 S -->
                <template slot="managerPerson" slot-scope="{ field, value }">
                  <div class="form-view-row">
                    <label>{{ field.displayName }}</label>
                    <div class="form-view-row-content" v-if="detailData.manager">
                      <span v-user="detailData.manager.userId" class="user-card-triggle">
                        <template v-if="isOpenData">
                          <open-data type="userName" :openid="detailData.manager.staffId"></open-data>
                        </template>
                        <template v-else>
                          {{ detailData.manager.displayName }}
                        </template>
                      </span>
                    </div>
                  </div>
                </template>
                <!-- 负责人 E -->

                <!-- 任务内容 S -->
                <template slot="missionContent" slot-scope="{ field, value }">
                  <div class="form-view-row">
                    <label>{{ field.displayName }}</label>
                    <div class="form-view-row-content"> {{ detailData.taskDesc }} </div>
                  </div>
                </template>
                <!-- 任务内容 E -->

                <!-- 任务状态 S -->
                <template slot="taskStatus" slot-scope="{ field, value }">
                  <div class="form-view-row">
                    <label>{{ field.displayName }}</label>
                    <div class="form-view-row-content">
                      <span class="status-tag" :style="stateBGC(detailData.taskStatus)">
                        {{ formatStatus(detailData.taskStatus) }}
                      </span>
                    </div>
                  </div>
                </template>
                <!-- 任务状态 E -->

                <!-- 任务类型 S -->
                <template slot="taskType" slot-scope="{ field, value }">
                  <div class="form-view-row">
                    <label>{{ field.displayName }}</label>
                    <div class="form-view-row-content"> 
                      <!-- {{ detailData.taskFormName }} -->
                      <span>{{ taskTypeMap[detailData.taskType] || '' }}/{{ detailData.taskFormName }}</span>
                    </div>
                  </div>
                </template>
                <!-- 任务类型 E -->

                <!-- TODO 前置任务 S -->
                <template slot="preTaskInfoList" slot-scope="{ field, value }">
                  <div class="form-view-row">
                    <label>{{ field.displayName }}</label>
                    <div class="form-view-row-content">
                      <span class="view-detail-btn" v-for="(item, i) in detailData.preTaskInfoList" :key="i" @click="openPreTask(item)">
                        {{ item.name }}
                        <i v-if="detailData.preTaskInfoList.length - 1 !== i">，</i>
                      </span>
                    </div>
                  </div>
                </template>
                <!-- 前置任务 E -->

                <!-- 项目编号 S -->
                <template slot="projectNumber" slot-scope="{ field, value }">
                  <div class="form-view-row">
                    <label>{{ field.displayName }}</label>
                    <div class="form-view-row-content" >
                      <span class="view-detail-btn" @click="openProjectViewTab(detailData)">
                        {{ detailData.projectNumber }}
                      </span>
                    </div>
                  </div>
                </template>
                <!-- 项目编号 E -->

            </form-view>
          </div>
        </el-tab-pane>
      </el-tabs>
     </div>

    <!-- 创建任务弹窗 -->
    <create-project-task 
    ref="CreateProjectTaskModal" 
    :project-id="detailData.projectId" 
    :template-id="detailData.projectTypeId" 
    @jumpPersonTab="jumpPersonTab"
    @updateList="getTaskData"></create-project-task>
  </div>
</template>
<script>
import * as ProjectManage from '@src/api/ProjectManage.ts';
import { toast } from '@src/util/platform';
import UpdateProgressDialog from '@src/modules/projectManage/taskManageView/components/UpdateProgressDialog.vue';
import projectTypeWorkLog from '@src/modules/projectManage/components/projectTypeWorkLog.vue';
import { formatStatus, stateBGC } from '@src/modules/projectManage/taskManageList/util/index';
import { taskTypeMap } from '@src/modules/projectManage/taskManageList/model';
/* enum */
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import CreateProjectTask from '@src/modules/setting/projectManage/components/TaskSettings/components/CreateProjectTask.vue'
/* util */
import { openAccurateTab } from '@src/util/platform';
import { t } from '@src/locales';
import _ from 'lodash';
import { useOpenTab } from '@src/modules/projectManage/taskManageList/hooks/useOpenTab';
const { openTaskManageViewTab } = useOpenTab();

export default {
  name: 'pro-task-tab',
  data() {
    return {
      activeName: 'record',
      formatStatus,
      stateBGC,
      taskTypeMap,
      fields: [],
      btnAuth: {},
      detailData: {},
      pageInit: false,
    }
  },
  computed:{
    isShowEdit() {
      // 只有工单在进行中，才可以更新进度, 工单审批中/草稿状态 隐藏按钮
      return this.task.state !=='draft' && this.task.inApprove !== 1 &&  this.detailData.hasEditAuth && (this.detailData?.taskStatus === 'NO_START' || this.detailData?.taskStatus === 'IN_PROGRESS') && this.detailData?.taskStatus !== 'CANCEL'
    },
    isTaskCancelState() {
      return this.detailData?.taskStatus === 'CANCEL'
    },
    // 工单的状态是否是已完成 未完成进度条不能拖到100
    canFinish() {
      let finishedStateArr = ['finished', 'costed', 'closed'];
      return finishedStateArr.indexOf(this.task.state) >= 0 || false;
    },
  },
  components: {
    [UpdateProgressDialog.name]: UpdateProgressDialog,
    projectTypeWorkLog,
    CreateProjectTask,
  },
  mounted() {
    // 获取任务表单数据
    this.getTaskData()
    // 获取表单固定字段
    this.getFieldList()
  },
  props: {
    // 项目的任务id
    projectTaskId: {
      type: String | Number,
      default: ''
    },
    task: {
      type: Object,
      default: (() => {})
    }
  },
  methods: {
    // 编辑工单类型任务
    editTaskDetail() {
      let editForm = _.cloneDeep(this.detailData)
      editForm.preTaskId = (editForm.preTaskInfoList || []).map((item) => (item.id))
      this.$refs.CreateProjectTaskModal.openDialog(editForm, true, 'edit')
    },

    jumpPersonTab() {
      this.$refs.CreateProjectTaskModal.closeDialog()
      this.$emit('jumpPersonTab');
    },
    getTaskData() {
      ProjectManage.taskDetailPro({id: this.projectTaskId}).then( async(res) => {
        if (!res.success) return this.$message.error(res.message)
        this.detailData = res.data || {}
        this.pageInit = true
        this.getBtnAuth() 
      })

    },
    openPreTask(item) {
      let fromId = window.frameElement?.getAttribute('id');

      if (item.taskType === 'WORK_TASK') {
        if (item.taskBizId) {
          openAccurateTab({
            type: PageRoutesTypeEnum.PageTaskView,
            key: item.taskBizId,
            // titleKey: taskFormName,
            params: 'noHistory=1',
            reload: true,
            fromId,
          })
        } else {
          this.$message.error(t('common.projectManage.editTip2'))
        }
      }else if(item.taskType === 'PAAS_TASK') {
        openTaskManageViewTab(item)
      } else {
        openAccurateTab({
          type: PageRoutesTypeEnum.PageTaskManageView,
          params: `id=${item.id}&projectId=${this.detailData.projectId}`,
          reload: true,
          key: item.id,
          fromId,
        });
      }
    },
    // 获取按钮权限
    getBtnAuth() {
      ProjectManage.projectTypeRoleBtn({projectId: this.detailData.projectId}).then((res) => {
        if (!res.success) return this.$message.error(res.message)
        this.btnAuth = res.data
      })
    },
    getFieldList() {
      this.fields = [
        {
          fieldName: 'taskNumber',
          displayName: t('projectManage.setting.taskSetting.taskNum'),
          width: '150px',
          formType: 'text',
          setting: {},
          isSystem: 1,
          isSearch: 1,
          tableName: 'mission',
        },
        {
          fieldName: 'missionName',
          displayName: t('projectManage.setting.taskSetting.taskName'),
          width: '150px',
          formType: 'text',
          setting: {},
          isSystem: 1,
          isSearch: 1,
          tableName: 'mission',
        },
        {
          fieldName: 'taskType',
          displayName: t('projectManage.setting.taskSetting.taskType'),
          width: '150px',
          formType: 'select',
          setting: {},
          isSystem: 1,
          isSearch: 0,
          tableName: 'mission',
        },
        {
          fieldName: 'taskStatus',
          displayName: t('projectManage.taskManageList.text3'),
          formType: 'select',
          isSystem: 1,
          isSearch: 1,
          tableName: 'mission',
        },
        {
          fieldName: 'preTaskInfoList',
          displayName: t('projectManage.taskManageList.text4'),
          formType: 'select',
          setting: {},
          isSystem: 1,
          isSearch: 0,
          tableName: 'mission',
        },
        {
          fieldName: 'projectTaskDesc',
          displayName: t('projectManage.setting.taskSetting.projectContent'),
          width: '150px',
          formType: 'text',
          setting: {},
          isSystem: 1,
          isSearch: 1,
          tableName: 'mission',
        },
        {
          fieldName: 'projectNumber',
          displayName: t('projectManage.taskManageList.text5'),
          formType: 'select',
          setting: {},
          isSystem: 1,
          isSearch: 0,
          tableName: 'mission',
        },
        {
          fieldName: 'projectName',
          displayName: t('projectManage.taskManageList.text6'),
          formType: 'select',
          setting: {},
          isSystem: 1,
          isSearch: 1,
          tableName: 'mission',
        },
      ];
    },
    UpdateProgress() {
      this.$refs.UpdateProgressDialog.openDialog()
    },
    async handelProgressSubmit(form) {
      const params = {
        ...form,
        id: this.detailData.id,
        projectId: this.detailData.projectId
      }
      await ProjectManage.updateTaskManageProgress(params).then((res) => {
        if (!res.success) return this.$message.error(res.message)
        this.$refs.UpdateProgressDialog.handleClose()
        toast(t('common.base.tip.updateSuccess'), 'success');
        // 刷新页面
        this.getTaskData()
      })
    },

    openProjectViewTab() {
      let fromId = window.frameElement?.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProjectManageView,
        params: `templateId=${this.detailData.projectTypeId}&id=${this.detailData.projectId}`,
        reload: true,
        fromId,
      });
    }
  }
}
</script>
<style lang="scss">
  .pro-task-detail {
    padding: 16px;
    .task-title-top {
      display: flex;
      align-items: center;
      justify-content: start;
    }
    .title-top-left {
      display: flex;
      align-items: center;
      .title-name {
        color: #333;
        font-size: 16px;
        font-weight: 500;
        font-family: PingFangSC-Medium, PingFang SC;
      }
      .el-progress {
        width: 200px;
        margin-left: 20px;

        ::v-deep .el-progress__text {
          color: rgba(0, 0, 0, 0.45);
        }
      }
    }
    .title-top-right {
      display: flex;
    }

    .tab-wrap {
      margin-top: 10px;
      .tab-item {
        margin: 20px 0 0 6px;
      }
    }
    .status-tag {
      padding: 0 8px;
      background-color: $color-ding-blue;
      line-height: 22px;
      border-radius: 22px;
      color: #fff;
      font-size: 12px;
      display: inline-block;
    }
  }
</style>